#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()

import requests, time, base64, json, datetime
import Crypto.Signature.PKCS1_v1_5 as sign_PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from typing import Union
from PyPDF2 import PdfReader, PdfWriter
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from pdf2image import convert_from_path
from PIL import Image
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

from equity_mall.utils.utils import random_str
from activities.models import Channel
from customers.utils import md5_rsa_sign


def rsa_long_encrypt(pub_key, message):
    rsakey = RSA.importKey(pub_key)
    cipher = sign_PKCS1_v1_5.new(rsakey)
    rand_hash = SHA256.new()
    rand_hash.update(message.encode())
    signature = cipher.sign(rand_hash)
    return str((base64.b64encode(signature)), encoding="utf-8")


def get_stockinfo(stock_id, platform):
    UFDODER_URL = f'https://api.mch.weixin.qq.com/v3/marketing/favor/stocks/{stock_id}?stock_creator_mchid={platform.mchid}'
    nonce_str = random_str()
    timestamp = int(time.time())
    pub_key = platform.pub_key
    message = f'GET\n/v3/marketing/favor/stocks/{stock_id}?stock_creator_mchid={platform.mchid}\n{timestamp}\n{nonce_str}\n\n'
    signature = rsa_long_encrypt(pub_key, message)
    headers = {
        'Authorization': f'WECHATPAY2-SHA256-RSA2048 mchid="{platform.mchid}",nonce_str="{nonce_str}",signature="{signature}",timestamp="{timestamp}",serial_no="{platform.serial_no}"',
    }
    response = requests.get(UFDODER_URL, headers=headers)
    data_dict = json.loads(response.content)
    return data_dict


def get_alidiscountcoupon(activityId, platform):
    url = 'https://dtbank.alipay.com/activity/pageQuery/queryOne.json'
    body = {
        'siteFrom': 'P',
        'queryRequest': '{"requestData":"' + activityId + '","activityScene":"CHANNEL_COMMON_VOUCHER","siteFrom":"P"}'
    }
    headers = {
        'Cookie': platform.cookie,
        'referer': 'https://p.alipay.com/'
    }
    response = requests.post(url, data=body, headers=headers)
    return response.json()


def get_meituan_acitivty(template_id, platform):
    # url = 'https://promo.meituan.com/api/open-platform/business/merchant/couponbatch/queryBatchInfo'
    # body = {"batchId": template_id}
    # headers = {'Cookie': platform.cookie, 'Content-Type': 'application/json'}
    # response = requests.post(url=url, json=body, headers=headers)
    # result = response.json()
    # return result
    url = 'https://promo.meituan.com/merchant/coupons/queryCouponBatchDetail'
    body = {
        "merchantId": 436,
        "batchId": int(template_id),
    }
    sign = md5_rsa_sign(body)
    body['sign'] = sign
    response = requests.post(url=url, json=body)
    return response.json()


def contract_add_stamp(output_path, mobile, sign_time, signature_copy):
    input_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), f'static/contract.pdf')
    watermark_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), f'static/watermark_{mobile}.pdf')
    typeface = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), f'static/fonts/LXGWNeoZhiSongCHS.ttf')
    stamp_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), f'static/signature_{mobile}.png')
    response = requests.get(url=signature_copy)
    with open(stamp_path, 'wb')as f:
        f.write(response.content)
    pdf_file = open(input_path, 'rb')
    pdf_reader = PdfReader(pdf_file)
    # 创建一个新的PDF页面，并将图片插入其中
    pdfmetrics.registerFont(TTFont('SimHei', typeface))
    c = canvas.Canvas(watermark_path, pagesize=letter)
    c.drawImage(stamp_path, 195, 430, width=60, height=100)
    c.setFont('SimHei', 16)
    c.drawString(200, 478, sign_time)
    c.save()
    stamp_file = open(watermark_path, 'rb')
    stamp_reader = PdfReader(stamp_file)
    stamp_page = stamp_reader.pages[0]

    with open(output_path, 'wb') as file:
        pdf_writer = PdfWriter(file)
        for page in range(len(pdf_reader.pages)):
            pdf_page = pdf_reader.pages[page]
            if page == 1:
                pdf_page.merge_page(stamp_page)
            pdf_writer.add_page(pdf_page)
            pdf_writer.write(file)
    pdf_file.close()
    stamp_file.close()
    os.remove(watermark_path)
    os.remove(stamp_path)


if __name__ == '__main__':
    # print(get_stockinfo('19449490', Channel.objects.get(id=4)))
    # print(get_meituan_acitivty('58687', Channel.objects.get(id=12)))

    contract_pdf = f'服务协议_{13510535265}.pdf'
    pdf_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), f'static/{contract_pdf}')
    contract_add_stamp(pdf_path, '13510535265', '2025-01-12', 'https://circle.sutpay.cn/Fhf7QVEFUiBPxNBszO3uOZpGRaXy')